package com.bc.trade.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bc.common.basemodel.BaseTransferQrcode;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

@SuppressWarnings("serial")
public class TransferQrcode extends BaseTransferQrcode<TransferQrcode> {
	
	public static final TransferQrcode dao = new TransferQrcode().dao();
	
	private Map<String, List<TransferQrcode>> qrcodeMap = new HashMap<>();

	public synchronized TransferQrcode selectQrcode(String amount) {
		List<TransferQrcode> list = qrcodeMap.get(amount);
		if (list == null || list.isEmpty()) {
			List<TradeOrder> orderList =  TradeOrder.dao.selecCreateTradeOrder();
			if (!orderList.isEmpty()) {
				StringBuffer sb = new StringBuffer();
				for (TradeOrder order: orderList) {
					if (StrKit.notBlank(order.getChannelOrderNo())) {
						sb.append("'" + order.getChannelOrderNo() + "',");
					}
				}
				sb.append("''");
				Db.use("admin").update("update transfer_qrcode set enable=TRUE where remark not in (" + sb.toString() +")");
			} else {
				List<TradeOrder> successOrderList =  TradeOrder.dao.selecSuccessTradeOrder();
				StringBuffer sb = new StringBuffer();
				for (TradeOrder order: successOrderList) {
					sb.append("'" + order.getChannelOrderNo() + "',");
				}
				sb.append("''");
				Db.use("admin").update("update transfer_qrcode set enable=TRUE where remark in (" + sb.toString() +")");
			}
			
			List<TransferQrcode> qrcodeList = TransferQrcode.dao.find("select * from transfer_qrcode where enable=TRUE");
			for(TransferQrcode qrcode : qrcodeList) {
				List<TransferQrcode> templist = qrcodeMap.get(qrcode.getAmount().toString());
				if (templist == null || templist.isEmpty()) {
					List<TransferQrcode> transferQrcodeList = new ArrayList<>();
					transferQrcodeList.add(qrcode);
					qrcodeMap.put(qrcode.getAmount().toString(), transferQrcodeList);
				} else {
					List<TransferQrcode> transferQrcodeList = qrcodeMap.get(qrcode.getAmount().toString());
					transferQrcodeList.add(qrcode);
					qrcodeMap.put(qrcode.getAmount().toString(), transferQrcodeList);
				}
			}
			
			if (qrcodeList.size() > 0) {
				Db.use("admin").update("update transfer_qrcode set enable=false");
			}
		}
		list = qrcodeMap.get(amount);
		if (list == null || list.isEmpty()) {
			return null;
		}
		
		TransferQrcode qrcode = list.get(0);
		list.remove(0);
		return qrcode;
	}
	
}
